package com.demo.practiceui.views.interactive;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * 自定义开关控件
 * 核心知识点：
 * 1. onTouchEvent - 处理点击和滑动
 * 2. ValueAnimator - 滑块平移动画
 * 3. 双状态切换逻辑
 * 4. 颜色渐变过渡
 */
public class CustomSwitchView extends View {

    // 开关状态
    private boolean isChecked = false;

    // 画笔
    private Paint trackPaint;       // 轨道画笔
    private Paint thumbPaint;       // 滑块画笔

    // 尺寸
    private int width;
    private int height;
    private float trackWidth = 180f;
    private float trackHeight = 90f;
    private float thumbRadius = 35f;
    private float thumbX;           // 滑块X坐标
    private float thumbY;           // 滑块Y坐标
    private float cornerRadius = 45f;

    // 颜色
    private int checkedColor = Color.parseColor("#4CAF50");
    private int uncheckedColor = Color.parseColor("#CCCCCC");
    private int currentTrackColor;

    // 动画
    private ValueAnimator thumbAnimator;
    private ValueAnimator colorAnimator;

    // 触摸相关
    private float touchDownX;
    private boolean isDragging = false;

    // 回调
    private OnCheckedChangeListener onCheckedChangeListener;

    public interface OnCheckedChangeListener {
        void onCheckedChanged(boolean isChecked);
    }

    public CustomSwitchView(Context context) {
        this(context, null);
    }

    public CustomSwitchView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomSwitchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 轨道画笔
        trackPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        trackPaint.setStyle(Paint.Style.FILL);
        currentTrackColor = uncheckedColor;

        // 滑块画笔
        thumbPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        thumbPaint.setColor(Color.WHITE);
        thumbPaint.setStyle(Paint.Style.FILL);
        thumbPaint.setShadowLayer(10, 0, 3, Color.parseColor("#50000000"));

        setLayerType(LAYER_TYPE_SOFTWARE, null);  // 开启阴影
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            width = (int) trackWidth + 40;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = (int) trackHeight + 40;
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        thumbY = height / 2f;

        // 初始化滑块位置
        if (isChecked) {
            thumbX = (width - thumbRadius - 15);
        } else {
            thumbX = thumbRadius + 15;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        float trackLeft = (width - trackWidth) / 2;
        float trackTop = (height - trackHeight) / 2;
        float trackRight = trackLeft + trackWidth;
        float trackBottom = trackTop + trackHeight;

        // 1. 绘制轨道
        trackPaint.setColor(currentTrackColor);
        RectF trackRect = new RectF(trackLeft, trackTop, trackRight, trackBottom);
        canvas.drawRoundRect(trackRect, cornerRadius, cornerRadius, trackPaint);

        // 2. 绘制滑块
        canvas.drawCircle(thumbX, thumbY, thumbRadius, thumbPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touchDownX = event.getX();
                isDragging = false;
                return true;

            case MotionEvent.ACTION_MOVE:
                float deltaX = Math.abs(event.getX() - touchDownX);
                if (deltaX > 10) {
                    isDragging = true;
                }
                return true;

            case MotionEvent.ACTION_UP:
                if (!isDragging) {
                    // 点击切换
                    toggle();
                } else {
                    // 根据滑动距离判断
                    float dragDistance = event.getX() - touchDownX;
                    if (Math.abs(dragDistance) > 30) {
                        setChecked(dragDistance > 0);
                    }
                }
                isDragging = false;
                return true;
        }

        return super.onTouchEvent(event);
    }

    /**
     * 切换状态
     */
    public void toggle() {
        setChecked(!isChecked);
    }

    /**
     * 设置开关状态（带动画）
     */
    public void setChecked(boolean checked) {
        if (isChecked == checked) {
            return;
        }

        isChecked = checked;

        // 滑块移动动画
        animateThumb();

        // 颜色渐变动画
        animateColor();

        // 回调
        if (onCheckedChangeListener != null) {
            onCheckedChangeListener.onCheckedChanged(isChecked);
        }
    }

    /**
     * 滑块移动动画
     */
    private void animateThumb() {
        if (thumbAnimator != null) {
            thumbAnimator.cancel();
        }

        float startX = thumbX;
        float endX = isChecked ? (width - thumbRadius - 15) : (thumbRadius + 15);

        thumbAnimator = ValueAnimator.ofFloat(startX, endX);
        thumbAnimator.setDuration(250);
        thumbAnimator.addUpdateListener(animation -> {
            thumbX = (float) animation.getAnimatedValue();
            invalidate();
        });
        thumbAnimator.start();
    }

    /**
     * 颜色渐变动画
     */
    private void animateColor() {
        if (colorAnimator != null) {
            colorAnimator.cancel();
        }

        int startColor = currentTrackColor;
        int endColor = isChecked ? checkedColor : uncheckedColor;

        colorAnimator = ValueAnimator.ofArgb(startColor, endColor);
        colorAnimator.setDuration(250);
        colorAnimator.addUpdateListener(animation -> {
            currentTrackColor = (int) animation.getAnimatedValue();
            invalidate();
        });
        colorAnimator.start();
    }

    /**
     * 获取开关状态
     */
    public boolean isChecked() {
        return isChecked;
    }

    /**
     * 设置监听器
     */
    public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
        this.onCheckedChangeListener = listener;
    }
}

